package com.linking.third.party.util;

import com.alibaba.fastjson.JSONObject;
import com.borealis.common.utils.StringUtils;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author YaoWeiXin
 * @Date 2020/4/9 11:00
 * @Description IOS工具类
 */
@Slf4j
public class IosUtils {

  private static final String url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
  private static final String url_verify = "https://buy.itunes.apple.com/verifyReceipt";

  /**
   * 苹果服务器验证
   *
   * @param receipt 账单
   * @return null 或返回结果 沙盒 https://sandbox.itunes.apple.com/verifyReceipt
   * @throws Exception public static String buyAppVerify(String receipt, boolean sandbox){ String
   *                   url = url_verify; if (sandbox) { url = url_sandbox; } JSONObject json = new
   *                   JSONObject(); json.put("receipt-data", receipt); PrintWriter out = null;
   *                   BufferedReader in = null; String result = ""; try { URL realUrl = new
   *                   URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); //
   *                   设置通用的请求属性 // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true);
   *                   // 设置 HttpURLConnection的字符编码 conn.setRequestProperty("Accept-Charset",
   *                   "UTF-8"); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream());
   *                   // 发送请求参数 out.print(json.toString()); // flush输出流的缓冲 out.flush(); //
   *                   定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new
   *                   InputStreamReader(conn.getInputStream())); String line; while ((line =
   *                   in.readLine()) != null) { result += line; } } catch (Exception e) {
   *                   logger.error(String.format("url:{%s} getResult :请求出现异常！%s", url,
   *                   e.getMessage())); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally {
   *                   try { if (out != null) { out.close(); } if (in != null) { in.close(); } }
   *                   catch (Exception ex) { ex.printStackTrace(); } } return result; }
   * @url 要验证的地址
   */

  public static String buyAppVerify(String receipt, String password, boolean sandbox) {
    String url = url_verify;
    if (sandbox) {
      url = url_sandbox;
    }
    return sendHttpsCoon(url, receipt, password);
  }

  /**
   * 发送请求
   *
   */
  private static String sendHttpsCoon(String url, String code, String password) {
    if (url.isEmpty()) {
      return null;
    }
    try {
      //设置SSLContext
      SSLContext ssl = SSLContext.getInstance("SSL");
      ssl.init(null, new TrustManager[]{myX509TrustManager}, null);
      //打开连接
      HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
      //设置套接工厂
      conn.setSSLSocketFactory(ssl.getSocketFactory());
      //加入数据
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-type", "application/json");

      JSONObject obj = new JSONObject();
      obj.put("receipt-data", code);
      if (StringUtils.isNotEmpty(password)) {
        obj.put("password", password);
      }

      BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
      buffOutStr.write(obj.toString().getBytes());
      buffOutStr.flush();
      buffOutStr.close();

      //获取输入流
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      String line = null;
      StringBuffer sb = new StringBuffer();
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
      return sb.toString();
    } catch (Exception e) {
      log.error(String.format("url:{%s} getResult :请求出现异常！%s", url, e.getMessage()));
      return "";
    }
  }

  /**
   * 重写X509TrustManager
   */
  private static TrustManager myX509TrustManager = new X509TrustManager() {
    @Override
    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    }
  };
}
